package com.example.demo.common.filter;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.demo.common.util.JwtUitls;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义过滤器
 * 缓存request
 * @author zuozhiwei
 */
@Component
public class RequestWrapperFilter extends OncePerRequestFilter {

    /**
     * 过滤器
     * 缓存request对象
     * @param httpServletRequest
     * @param httpServletResponse
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @SuppressWarnings("all")
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //filterChain.doFilter(new ContentCachingRequestWrapper(httpServletRequest), httpServletResponse);

        Map<String,String> map = new HashMap<>();
        String url =  ((HttpServletRequest)httpServletRequest).getRequestURI();
        String method = httpServletRequest.getMethod();
//        if (method.equalsIgnoreCase("OPTIONS")) {
//            httpServletResponse.getOutputStream().write("Success".getBytes("utf-8"));
//        } else {
//            filterChain.doFilter(httpServletRequest, httpServletResponse);
//        }
        if(url != null){
            if ("OPTIONS".equals(httpServletRequest.getMethod())){
                filterChain.doFilter(new ContentCachingRequestWrapper(httpServletRequest),httpServletResponse);
                return;
            }
            //登录请求直接放行
            if("/smartLamp/user/login".equals(url) || "/SSEtest/orderpay".equals(url) || "/SSEtest/payback".equals(url) || "/SSEtest/putVideoAndImage".equals(url) || "/doc.html".equals(url) || "/favicon.ico".equals(url) || "/webjars".equals(url.substring(0, 8)) || "/swagger-resources".equals(url) || "/v2".equals(url.substring(0, 3))){
                filterChain.doFilter(new ContentCachingRequestWrapper(httpServletRequest),httpServletResponse);
                return;
            }else{
                //其他请求验证token
                String token = ((HttpServletRequest)httpServletRequest).getHeader("token");
                if(StringUtils.isNotBlank(token)){
                    //token验证结果
                    int verify  = JwtUitls.verify(token);
                    if(verify != 1){
                        //验证失败
                        if(verify == 2){
                            map.put("errorMsg","token已过期");
                        }else if(verify == 0){
                            map.put("errorMsg","用户信息验证失败");
                        }
                    }else if(verify  == 1){
                        //验证成功，放行
                        filterChain.doFilter(httpServletRequest,httpServletResponse);
                        return;
                    }
                }else{
                    //token为空的返回
                    map.put("errorMsg","未携带token信息");
                }
            }
            JSONObject jsonObject = new JSONObject(map);
            httpServletResponse.setContentType("application/json");
            //设置响应的编码
            httpServletResponse.setCharacterEncoding("utf-8");

            // 此处 setHeader、addHeader 方法都可用。但 addHeader时写多个会报错：“...,but only one is allowed”
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
//        response.addHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
            // 解决预请求（发送2次请求），此问题也可在 nginx 中作相似设置解决。
            httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Cache-Control,Pragma,Content-Type,Token, Content-Type");
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");

            //响应
            PrintWriter pw=httpServletResponse.getWriter();
            pw.write(jsonObject.toString());
            pw.flush();
            pw.close();
        }
    }
}
